package com.aidong.carnival.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aidong.activity.dao.MstCampaignDao;
import com.aidong.activity.entity.MstCampaign;
import com.aidong.carnival.dao.ActivityDao;
import com.aidong.carnival.dao.InvitationDao;
import com.aidong.carnival.entity.Activity;
import com.aidong.carnival.entity.Message;
import com.aidong.carnival.service.ActivityService;
import com.aidong.jobs.constants.JobConst;
import com.aidong.pay.config.util.ClenderUtil;
import com.aidong.pay.dao.OrdergeneratedDao;
import com.aidong.util.bus.CodeConsts;

@Service
public class ActivityServiceImpl implements ActivityService {
	@Autowired
	ActivityDao activityDao;
	
	@Autowired
	InvitationDao invitationDao;
	
	@Autowired
	MstCampaignDao mstCampaignDao;
	@Autowired
	private OrdergeneratedDao ordergeneratedDao;

	@Override
	public List<Activity> single() {
		return activityDao.single();
	}

	@Override
	public List<Activity> pack() {
		return activityDao.pack();
	}

	@Override
	public List<Activity> vip() {
		return activityDao.vip();
	}
	@Transactional(rollbackFor = { Exception.class })
	@Override
	public Message addBuy(int listType,String[] ids,String idongId,String contactName,String contactPhone,int cityId, int addressId,HttpServletRequest request) throws Exception{
		MstCampaign campaign=new MstCampaign();
		campaign.setCityId(cityId);
		StringBuffer sb=new StringBuffer();
		Message ms=new Message();
		campaign.setIdongId(idongId); // 爱动号
		//int campaignId = campaign.getCampaignId(); // 活动ID
		// 解密联系人电话
		campaign.setContactPhone(contactPhone);
		campaign.setContactName(contactName);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		int season=0;
		int num=0;
		int ticketCou=0;//票总
		
		if(listType==1){
			num=1;//单票数量
			ticketCou=5;
		}else if(listType==2){
			num=4;//套票数量
			ticketCou=6;
		}else if(listType==3){
			num=8;//VIP票数量
			ticketCou=7;
		}else if(listType==4){
			ticketCou=11;//爱动训练营(单独)
		}else if(listType==5){
			ticketCou=12;//幸运抽奖
			//判断是否存在幸运抽奖，如果没有则添加
			int re=mstCampaignDao.getLuckyCampaignCou();
			if(re==0){
				/**
				 * 购买邀请码活动
				 */
				return addinvitationBuy(idongId,contactName,contactPhone);
			}
			//查询是否有该时间段的幸运抽奖
			Map<String,Object> count=mstCampaignDao.getActuallyTime();
			if(count==null){
				//获取下一场活动
				Map<String,Object> luckyMap=mstCampaignDao.getActuallyNextTime();
				if(luckyMap==null){
					ms.setCode(0);
					ms.setMessage("活动已结束");
					return ms;
				}else{
					ms.setCode(0);
					ms.setMessage("第"+luckyMap.get("sort")+"场活动还未开始！");
					return ms;
				}
			}else{
				season=Integer.parseInt(count.get("sort").toString());
			}
			double price=mstCampaignDao.getLuckyDrawPrice();
			Map<String,Object> moneyMap=new HashMap<String,Object>();
			moneyMap.put("time", sdf.format(new Date()));
			moneyMap.put("idongId", idongId);
			//判断是否有资格购买
			double money=mstCampaignDao.getActuallyCount(moneyMap);
			if(money<price){
				ms.setCode(0);
				ms.setMessage("您还没有资格参加该次抽奖");
				return ms;
			}
			//判断是否已参加该抽奖
			int cou=mstCampaignDao.getLuckyDrawCount(Integer.parseInt(idongId));
			if(cou>0){
				ms.setCode(0);
				ms.setMessage("您已参加过该次抽奖");
				return ms;
			}
			
		}
		
		String sysDate = sdf.format(new Date());
		Date formatDate = sdf.parse(sysDate); // 系统当前年月日

		// 获得活动报名结束时间、报名人数、可参加人数
		Map<String, Object> msgMap = null;
		String signStratTime ="";  // 活动报名开始时间
		Date stratDateTime =null; 
		String signEndTime = ""; // 活动报名截止时间
		Date endDateTime =null; 
		int allowPerson = 0; // 活动可报名人数
		int signPerson = 0; // 活动报名有效人数（已报名人数）
		int version=0;
		if(listType==4 || listType==5){
			//需求变更后可取单条数据
			List<MstCampaign> list=mstCampaignDao.getCampaignAiDongList(ticketCou);
			num=list.size();
			if(num==0){
				ms.setCode(0);
				ms.setMessage("无该活动信息");
				return ms;
			}
			ids=new String[num];
			for(int i=0;i<num;i++){
				ids[i]=list.get(i).getCampaignId()+"";
			}
		}
		
		if (ids.length > 0 && (!"".equals(contactName) && contactName != null)
				&& (!"".equals(contactPhone) && contactPhone != null)) {
			
			Map<String,Object> paraMap=new HashMap<String,Object>();
			MstCampaign campaignDetail=null;
			for(int i=0;i<num;i++){
				msgMap = mstCampaignDao.getCampaignSignMsg(Integer.parseInt(ids[i]));
				if(msgMap==null){
					ms.setCode(0);
					ms.setMessage("无该活动信息");
					return ms;
				}
				//根据爱动号和活动ID查看是否已预约过该活动
				paraMap=new HashMap<String, Object>();
				paraMap.put("campaignId", Integer.parseInt(ids[i]));
				paraMap.put("idongId", idongId);
				List<Map<String, Object>> alreayMap = mstCampaignDao.getCarnivalIfAlreadyReg(paraMap);
				if (alreayMap.size() > 0) { // 是否已有报名记录
					for (Map<String, Object> alreay : alreayMap) {
						int alreayStatus = Integer.parseInt(alreay.get("status").toString());
						if (alreayStatus == CodeConsts.CODE_STATIC_BOOKING_BOOKING) { // 已预约状态
							ms.setCode(0);
							ms.setMessage("您已报名该活动，请到订单列表查看");
							return ms;
						}
					}
				}
				signStratTime = msgMap.get("stratSignTime").toString(); // 活动报名开始时间
				stratDateTime = sdf.parse(signStratTime);
				signEndTime = msgMap.get("endSignTime").toString(); // 活动报名截止时间
				endDateTime = sdf.parse(signEndTime);
				//brandId = Integer.valueOf(msgMap.get("brandId").toString());
				allowPerson = Integer.parseInt(msgMap.get("allowPerson").toString()); // 活动可报名人数
				signPerson = mstCampaignDao.getCampaignValidCount(Integer.parseInt(ids[i])); // 活动报名有效人数（已报名人数）
				if(signPerson>=allowPerson){
					ms.setCode(0);
					ms.setMessage(msgMap.get("campaignTitle").toString()+"报名人数已满");
					return ms;
				}
				if(formatDate.compareTo(endDateTime) == 1 || formatDate.compareTo(stratDateTime) == -1){
					ms.setCode(0);
					ms.setMessage("活动："+msgMap.get("campaignTitle").toString()+"不在活动报名时间范围之内");
					return ms;
				}
				
				//根据活动ID获取该活动是否预约已满
				paraMap=new HashMap<String, Object>();
				paraMap.put("campaignId", ids[i]);
				campaignDetail=mstCampaignDao.getFullByCampaignId(paraMap);
				if(campaignDetail==null){
					ms.setCode(0);
					ms.setMessage("无该活动");
					return ms;
				}
				if(Integer.parseInt(campaignDetail.getIsFull())==1){
					ms.setCode(0);
					ms.setMessage(campaignDetail.getCampaignTitle()+"报名人数已满");
					return ms;
				}
				sb.append(campaignDetail.getCampaignTitle()+"、");
				
			}
			Map<String,Object> map=new HashMap<String, Object>();
			StringBuffer sub=new StringBuffer();
			for(int i=0;i<num;i++){
				msgMap =null;
				msgMap = mstCampaignDao.getCampaignSignMsg(Integer.parseInt(ids[i]));
				signStratTime = msgMap.get("stratSignTime").toString(); // 活动报名开始时间
				stratDateTime = sdf.parse(signStratTime);
				signEndTime = msgMap.get("endSignTime").toString(); // 活动报名截止时间
				endDateTime = sdf.parse(signEndTime);
				//brandId = Integer.valueOf(msgMap.get("brandId").toString());
				allowPerson = Integer.parseInt(msgMap.get("allowPerson").toString()); // 活动可报名人数
				signPerson = mstCampaignDao.getCampaignValidCount(Integer.parseInt(ids[i])); // 活动报名有效人数（已报名人数）
				version=Integer.parseInt(msgMap.get("version").toString());
				/**
				 * 查询该活动是否已报满
				 */
				paraMap=new HashMap<String,Object>();
				paraMap.put("campaignId", Integer.parseInt(ids[i]));
				paraMap.put("version", version);
				campaignDetail=mstCampaignDao.getFullByCampaignId(paraMap);
				if(campaignDetail ==null || Integer.parseInt(campaignDetail.getIsFull())==1){
					throw new Exception();
				}else{ 
					paraMap.put("signPerson", signPerson);
					paraMap.put("allowPerson", allowPerson);
					
					int result=mstCampaignDao.updateFullByCampaignId(paraMap);
					if(result==0){
						throw new UnsupportedOperationException();
					}
				}
				
				campaign.setMovieFlg(0);
				campaign.setCampaignId(Integer.parseInt(ids[i]));
				if(listType!=4 && listType!=5){
					// 添加预约信息
					mstCampaignDao.addActivityReg(campaign);
					sub.append(campaign.getSubscribeId()+",");//记录预约ID
				}
				//最后一个活动
				if(i==num-1){
					double price=0.00;
					Map<String, Object> payMap = new HashMap<String, Object>();
					payMap.put("typeCou", ticketCou);
					campaignDetail=mstCampaignDao.getCarnivalByType(payMap);
					campaign.setCampaignId(campaignDetail.getCampaignId());//将嘉年华总的活动
					price=campaignDetail.getCamPrice();
					String title="";
					if(listType!=4 && listType!=5){
						//根据地址ID获取地址信息
						Map<String,Object> addMap=mstCampaignDao.getAddressDetailById(addressId);
						if(addMap!=null){
							campaign.setAddress(addMap.get("address").toString());
							campaign.setNameAddress(addMap.get("name").toString());
							campaign.setMobileAddress(addMap.get("phone").toString());
							campaign.setSelectAddressId(addressId);
						}
						title= campaignDetail.getCampaignTitle()+"("+sb.toString().substring(0,sb.length()-1)+")";
					}else{
						
						title= campaignDetail.getCampaignTitle();
					}
					if(listType==5){
						int person=mstCampaignDao.getLuckyDrawOnce();
						if(person>=2){
							ms.setCode(0);
							ms.setMessage("该时间段抢购已完成");
							return ms;
						}else{
							if(JobConst.activeMap.containsKey(idongId)){
								ms.setCode(0);
								ms.setMessage("请勿重复操作");
								return ms;
							}
							JobConst.activeMap.put(idongId, System.currentTimeMillis());
						}
						campaign.setQuantity(season);
					}
					// 添加预约信息
					mstCampaignDao.addActivityReg(campaign);
					int subscribeId = campaign.getSubscribeId(); // 预约ID
					// 添加付款信息
					payMap=new HashMap<String, Object>();
					payMap.put("subscribeId", subscribeId);
					payMap.put("orderType", 1);
					payMap.put("amount",price);
					payMap.put("title",title);
					payMap.put("idongId", campaign.getIdongId());
					payMap.put("nickName", campaign.getContactName());
					payMap.put("phone", campaign.getContactPhone());
					
					if(listType!=4 && listType!=5){
						payMap.put("carnivalSubscribeIds", sub.toString().substring(0,sub.length()-1));
					}
					if(listType==5){
						payMap.put("status",1);
						payMap.put("processId",2);
						payMap.put("tickNo",ClenderUtil.electronicTicketNo(campaign.getContactPhone())); // 电子券号
					}else{
						payMap.put("status",0);
						payMap.put("processId",1);
					}
					
					
					ordergeneratedDao.addCarnivalCampaginOrderPay(payMap);
					String orderId = payMap.get("orderId").toString();
					if(listType==5){
						ms.setCode(0);
						ms.setMessage("恭喜您，抢购已成功");
						return ms;
					}
					
					map.put("subscribeId", subscribeId);
					map.put("orderId", orderId);
					map.put("zhifubao", true);
					map.put("weixin", true);
					map.put("voucher", false);
					map.put("exchange", false);
					map.put("membership", false);
					map.put("discount", false);
					map.put("price", price);
					map.put("campaignId", campaignDetail.getCampaignId());
					map.put("CampaignStartTime", campaignDetail.getCampaignTime());
					map.put("title", title);
				}
			}
			ms.setCode(1);
			ms.setMap(map);
			return ms;
		} else {
			ms.setCode(0);
			ms.setMessage("参数缺失");
			return ms;
		}
		
	}
	public Message addinvitationBuy(String idongId,String contactName,String contactPhone)throws Exception {
		Message ms=new Message();
		MstCampaign campaign=new MstCampaign();
		
		campaign.setIdongId(idongId); // 爱动号
		//int campaignId = campaign.getCampaignId(); // 活动ID
		// 解密联系人电话
		campaign.setContactPhone(contactPhone);
		campaign.setContactName(contactName);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String sysDate = sdf.format(new Date());
		Date formatDate = sdf.parse(sysDate); // 系统当前年月日

		// 获得活动报名结束时间、报名人数、可参加人数
		Map<String, Object> msgMap = null;
		String signStratTime ="";  // 活动报名开始时间
		Date stratDateTime =null; 
		String signEndTime = ""; // 活动报名截止时间
		Date endDateTime =null; 
		int allowPerson = 0; // 活动可报名人数
		int signPerson = 0; // 活动报名有效人数（已报名人数）
		int version=0;
		int activitId=0;
		//需求变更后可取单条数据
		List<MstCampaign> list=mstCampaignDao.getCampaignAiDongList(13);
		if(list.size()==0){
			ms.setCode(0);
			ms.setMessage("无该活动邀请信息");
			return ms;
		}
		activitId=list.get(0).getCampaignId();
		
		int count=invitationDao.getInvitationCount(contactPhone,activitId);
		if(count==0){
			ms.setCode(0);
			ms.setMessage("预约手机号与该用户绑定的手机号不一致");
			return ms;
		}
		if (activitId > 0 && StringUtils.isNotBlank(contactName)
				&& StringUtils.isNotBlank(contactPhone)) {
			
			Map<String,Object> paraMap=new HashMap<String,Object>();
			MstCampaign campaignDetail=null;
			msgMap = mstCampaignDao.getCampaignSignMsg(activitId);
			if(msgMap==null){
				ms.setCode(0);
				ms.setMessage("无该活动信息");
				return ms;
			}
			//根据爱动号和活动ID查看是否已预约过该活动
			paraMap=new HashMap<String, Object>();
			paraMap.put("campaignId",activitId);
			paraMap.put("idongId", idongId);
			List<Map<String, Object>> alreayMap = mstCampaignDao.getCarnivalIfAlreadyReg(paraMap);
			if (alreayMap.size() > 0) { // 是否已有报名记录
				for (Map<String, Object> alreay : alreayMap) {
					int alreayStatus = Integer.parseInt(alreay.get("status").toString());
					if (alreayStatus == CodeConsts.CODE_STATIC_BOOKING_BOOKING) { // 已预约状态
						ms.setCode(0);
						ms.setMessage("您已报名该活动，请到订单列表查看");
						return ms;
					}
				}
			}
			signStratTime = msgMap.get("stratSignTime").toString(); // 活动报名开始时间
			stratDateTime = sdf.parse(signStratTime);
			signEndTime = msgMap.get("endSignTime").toString(); // 活动报名截止时间
			endDateTime = sdf.parse(signEndTime);
			allowPerson = Integer.parseInt(msgMap.get("allowPerson").toString()); // 活动可报名人数
			signPerson = mstCampaignDao.getCampaignValidCount(activitId); // 活动报名有效人数（已报名人数）
			if(signPerson>=allowPerson){
				ms.setCode(0);
				ms.setMessage(msgMap.get("campaignTitle").toString()+"报名人数已满");
				return ms;
			}
			if(formatDate.compareTo(endDateTime) == 1 || formatDate.compareTo(stratDateTime) == -1){
				ms.setCode(0);
				ms.setMessage("活动："+msgMap.get("campaignTitle").toString()+"不在活动报名时间范围之内");
				return ms;
			}
			
			//根据活动ID获取该活动是否预约已满
			paraMap=new HashMap<String, Object>();
			paraMap.put("campaignId",activitId);
			campaignDetail=mstCampaignDao.getFullByCampaignId(paraMap);
			if(campaignDetail==null){
				ms.setCode(0);
				ms.setMessage("无该活动");
				return ms;
			}
			if(Integer.parseInt(campaignDetail.getIsFull())==1){
				ms.setCode(0);
				ms.setMessage(campaignDetail.getCampaignTitle()+"报名人数已满");
				return ms;
			}
			msgMap =null;
			msgMap = mstCampaignDao.getCampaignSignMsg(activitId);
			signStratTime = msgMap.get("stratSignTime").toString(); // 活动报名开始时间
			stratDateTime = sdf.parse(signStratTime);
			signEndTime = msgMap.get("endSignTime").toString(); // 活动报名截止时间
			endDateTime = sdf.parse(signEndTime);
			//brandId = Integer.valueOf(msgMap.get("brandId").toString());
			allowPerson = Integer.parseInt(msgMap.get("allowPerson").toString()); // 活动可报名人数
			signPerson = mstCampaignDao.getCampaignValidCount(activitId); // 活动报名有效人数（已报名人数）
			version=Integer.parseInt(msgMap.get("version").toString());
			/**
			 * 查询该活动是否已报满
			 */
			paraMap=new HashMap<String,Object>();
			paraMap.put("campaignId",activitId);
			paraMap.put("version", version);
			campaignDetail=mstCampaignDao.getFullByCampaignId(paraMap);
			if(campaignDetail ==null || Integer.parseInt(campaignDetail.getIsFull())==1){
				throw new Exception();
			}else{ 
				paraMap.put("signPerson", signPerson);
				paraMap.put("allowPerson", allowPerson);
				int result=mstCampaignDao.updateFullByCampaignId(paraMap);
				if(result==0){
					throw new UnsupportedOperationException();
				}
			}
			
			campaign.setMovieFlg(0);
			campaign.setCampaignId(activitId);
			
			double price=0.00;
			Map<String, Object> payMap = new HashMap<String, Object>();
			payMap.put("typeCou", 13);
			campaignDetail=mstCampaignDao.getCarnivalByType(payMap);
			campaign.setCampaignId(campaignDetail.getCampaignId());//将嘉年华总的活动
			price=campaignDetail.getCamPrice();
			String title= campaignDetail.getCampaignTitle();
			// 添加预约信息
			mstCampaignDao.addActivityReg(campaign);
			int subscribeId = campaign.getSubscribeId(); // 预约ID
			// 添加付款信息
			payMap=new HashMap<String, Object>();
			payMap.put("subscribeId", subscribeId);
			payMap.put("orderType", 1);
			payMap.put("amount",price);
			payMap.put("title",title);
			payMap.put("idongId", campaign.getIdongId());
			payMap.put("nickName", campaign.getContactName());
			payMap.put("phone", campaign.getContactPhone());
			
			payMap.put("status",0);
			payMap.put("processId",1);
			payMap.put("tickNo",ClenderUtil.electronicTicketNo(campaign.getContactPhone())); // 电子券号
			
			
			ordergeneratedDao.addCarnivalCampaginOrderPay(payMap);
			String orderId = payMap.get("orderId").toString();
			/*ms.setCode(0);
			ms.setMessage("恭喜您，预约已成功");
			return ms;*/
			Map<String,Object> map=new HashMap<String, Object>();	
			map.put("subscribeId", subscribeId);
			map.put("orderId", orderId);
			map.put("zhifubao", true);
			map.put("weixin", true);
			map.put("voucher", false);
			map.put("exchange", false);
			map.put("membership", false);
			map.put("discount", false);
			map.put("price", price);
			map.put("campaignId", campaignDetail.getCampaignId());
			map.put("CampaignStartTime", campaignDetail.getCampaignTime());
			map.put("title", title);
			ms.setCode(1);
			ms.setMap(map);
			return ms;
		} else {
			ms.setCode(0);
			ms.setMessage("参数缺失");
			return ms;
		}
	}
}
